package service.impl;


import Dto.GoodsDto;
import cqcet.aibd.soft.DbUtil;
import dao.GoodsDAO;
import dao.impl.GoodsDAOImpl;
import model.Goods;
import model.User;
import service.GoodsService;
import service.OrderService;
import service.UserService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 商品服务层
 * 处理商品模块的相关业务逻辑
 */
public class GoodsServiceImpl implements GoodsService {

    private final GoodsDAO goodsDAO;

    private final OrderService orderService = new OrderServiceImpl();

    private final UserService userService = new UserServiceImpl();

    public GoodsServiceImpl() {
        goodsDAO = new GoodsDAOImpl();
    }

    @Override
    public int buyGoods(User user, GoodsDto goodsDto) {
        Connection con = null;
        int i = -1;
        try {
            // 获取数据库连接对象
            con = DbUtil.getConnection();
            // 关闭事务自动提交 开启手动事务
            con.setAutoCommit(false);

            // 修改用户余额
            userService.updateUserBalance(con, user, 2, goodsDto.getNum() * goodsDto.getPrice());

            // 修改商品库存
            updateGoodsStock(con, goodsDto, 2, goodsDto.getNum());

            // 添加订单
            i = orderService.addOrder(con, user, goodsDto);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                // 出现异常回滚事务
                Objects.requireNonNull(con).rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            try {
                // 提交事务
                Objects.requireNonNull(con).commit();
                // 完成事务以后将事务设置会自动提交
                Objects.requireNonNull(con).setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                // 关闭连接
                Objects.requireNonNull(con).close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 添加订单
        return i;

    }

    @Override
    public int addAGoods(Goods goods) {
        return goodsDAO.addGoods(goods);
    }

    @Override
    public int delAGoods(String id) {
        return goodsDAO.deleteGoods(id);
    }

    @Override
    public int updateGoods(String id, Goods goods) {
        return goodsDAO.updateGoods(id, goods);
    }

    /**
     * 获取商品详情
     * <p>
     * 1.根据商品ID获取商品对象
     * 2.若该对象存在则返回，否则返回null
     *
     * @return Goods对象，或null
     */
    @Override
    public Goods findAGoodsById(String id) {
        return goodsDAO.getGoodsById(id);
    }

    @Override
    public List<Goods> findGoodsByIds(String ids) throws Exception {
        List<Goods> allGoods = getGoodsListDb();
        List<Goods> goodList = new ArrayList<>();
        goodList.addAll(allGoods);

        return goodList;
    }

    @Override
    public List<Goods> getGoodsListDb() throws Exception {
        return goodsDAO.getGoodsList();
    }

    @Override
    public List<Goods> findGoodsByName(String name) {
        return goodsDAO.getGoodsByName(name);
    }

    @Override
    public Boolean checkUserBalanceAndGoodsStockEnough(User user, GoodsDto goodsDto) {
        Goods g = goodsDAO.getGoodsById(goodsDto.getId());
        // 商品总金额
        Double sum = goodsDto.getNum() * g.getPrice();

        // 获取用户余额
        return ((user.getBalance() < sum) || (goodsDto.getNumber() < goodsDto.getNum()));
    }

    @Override
    public int updateGoodsStock(Connection con, Goods goods, Integer flag, Integer num) throws Exception {

        return goodsDAO.updateGoodsStock(con, goods, flag, num);
    }


    @Override
    public int updateGoodsStock(Goods goods, Integer flag, Integer num) {

        return goodsDAO.updateGoodsStock(goods, flag, num);
    }
}
